// composite custom server control class for KUAMStockTicker

using System;
using CStock;
using NUnit.Framework;

using System.Diagnostics;


using System.Xml;
using System.Xml.Xsl;
using System.Net;
using System.IO;

using System.Globalization;


namespace CStock
{
	[TestFixture] 
	public class StockTicker //: Control, INamingContainer
	{        
		// private data members
		private string _symbols;
		private string _path;
		private int _hoursDiff;
        
		// public properties 
		public string StockSymbols
		{
			get { return _symbols; }
			set { _symbols = value; }
		}
		[Test] 
		public void NasdaqNew()
		{
            return;
            ////does not work any more ...
            //System.Xml.XmlDocument m_xmlFeed = new System.Xml.XmlDocument();
            //string symbol = "SI";
            //symbol = "MSFT";
            // m_xmlFeed.RemoveAll();
            //string query = "http://quotes.nasdaq.com/Quote.dll?mode=stock&symbol=";
            //query=query+symbol+"&&quick.x=0&quick.y=0";

            // m_xmlFeed.Load(query);
            ////m_xmlFeed.Load(@"http://quotes.nasdaq.com/quote.dll?page=xml&mode=stock&symbol=" +  symbol);
            //System.Xml.XmlNode xmlNode;
            //try
            //{
            //    xmlNode = m_xmlFeed.SelectSingleNode("//issue-name");
            //    string name = xmlNode.InnerText;

            //    xmlNode = m_xmlFeed.SelectSingleNode("//last-sale-price");
            //    string lastSale = xmlNode.InnerText;
            //    xmlNode = m_xmlFeed.SelectSingleNode("//net-change-pct");
            //    string change = xmlNode.InnerText;

            //}
            //catch(Exception exc)
            //{
            //    Debug.Assert(false, exc.Message);
            //}
                        


		}
		[Test] 
		public void GetSomeQuotes()
		{
			//string str = "MSFT";//IBM, AMZN
			//nasdaq string=
			//http://quotes.nasdaq.com/quote.dll?mode=stock&page=xml&symbol=MSFT&symbol=SUNW&symbol=INTC&symbol=DIS&symbol=AOLA&symbol=CSCO&symbol=ADBE&symbol=CMCSA&symbol=EBAY&symbol=SBUX 

            //does not work any more

			//double val = GetQuote(str);
			//Debug.WriteLine(val.ToString());
            

		}

		protected double GetQuote(string symbol)
		{
			string a;
			string b;
			string c="";
			string d="";               
			string query = "http://quotes.nasdaq.com/Quote.dll?mode=stock&symbol=";

			query=query+symbol+"&&quick.x=0&quick.y=0";

			
			WebRequest wrq = WebRequest.Create(query);

			// Return the response. 

			WebResponse wr= wrq.GetResponse();

			StreamReader sr = new StreamReader(wr.GetResponseStream(), System.Text.Encoding.ASCII);

			a=sr.ReadToEnd().ToString();

 

			if(a.IndexOf(symbol)>0)

			{

				int pos1=a.IndexOf("$&nbsp;");

				//int pos2=a.IndexOf("]"); 

				b=a.Substring(pos1,50);

				c=b.Substring(7,b.Length-8);

				int pos2=c.IndexOf("</td>");

				d = c.Substring(0,pos2);

			} 

			wr.Close();

			sr.Close(); 

			CultureInfo ci = new CultureInfo("en-US");
			return(Convert.ToDouble(d, ci));

		}

		[Test] 
		public void GetStockFromWeb()
		{
            return;
            //does not work any more
		
//            StockSymbols = "SIE";
//            this.StockSymbols = "MSFT;SUNW;INTC;DIS;AOLA;CSCO;ADBE;CMCSA;EBAY;SBUX";
//            GetStockSymbols(StockSymbols);

			

//            // STEP 2: get the XML data from NASDAQ and parse it, formatting it with a custom XSLT stylesheet
//            XmlDocument doc = new XmlDocument();
//            XslCompiledTransform transformXSL = new XslCompiledTransform();
//            doc.Load(nasdaqSearchString);
//            transformXSL.Load(XSLSource);
////			Xml xmlStockData = new Xml();
////			xmlStockData.Document = doc;
////			xmlStockData.Transform = transform;

		}
		public string XSLSource
		{
			get 
			{ 
				return this._path;
			}
			set 
			{ 
				_path = value; 
			}
		}
        
//		public string BackgroundColor
//		{
//			get { string userColor = (_color == null || _color == string.Empty) ? "beige" : _color; return userColor; } 
//			set { _color = value; } 
//		}
        
		public int TimeDiffFromEST
		{
			get { int hours = (_hoursDiff != 0) ? _hoursDiff : 0; return hours; }
			set { _hoursDiff = value; }
		}
        
		// string to query NASDAQ's database
		private string nasdaqSearchString = "http://quotes.nasdaq.com/quote.dll?mode=stock&page=xml";
        
		// private class-level method
		private string GetStockSymbols(string stocks)
		{
			string[] arrSymbols = stocks.Split(new char[] {';'});
			foreach(string stock in arrSymbols)
			{
				nasdaqSearchString += "&symbol=" + stock;
			}
			return nasdaqSearchString;
		}
        
		// no need to override the base class Render() method, because the rendering is completed within the child controls
//		protected override void CreateChildControls()
//		{
//			// STEP 1: get the query string to use against the NASDAQ data store
//			GetStockSymbols(StockSymbols);
//            
//			// STEP 2: get the XML data from NASDAQ and parse it, formatting it with a custom XSLT stylesheet
//			XmlDocument doc = new XmlDocument();
//			XslTransform transform = new XslTransform();
//			doc.Load(nasdaqSearchString);
//			transform.Load(XSLSource);
//			Xml xmlStockData = new Xml();
//			xmlStockData.Document = doc;
//			xmlStockData.Transform = transform;
//            
//			// STEP 3: write a client-side JavaScript function to reload the control every 20 minutes, and then register this script block to the page framework
//			// (this process reloads the custom control ONLY, without having to reload the entire page)
//			string code = "<!-- REFRESH THE STOCK TICKER EVERY 20 MINUTES -->\n\t\t";
//			code += "<script language=\"JavaScript\">\n\t\t\t";
//			code += "var intervalID;\n\t\t\t";
//			code += "intervalID = window.setInterval(\"refreshStockTicker()\",1200000);\n\t\t\t";	
//			code += "function refreshStockTicker() {document.execCommand(\"Refresh\");}\n\t\t";
//			code += "</script>\n\t\n\n\n";
//			if(!Page.IsClientScriptBlockRegistered("refreshCode"))
//			{
//				Page.RegisterClientScriptBlock("refreshCode",code);
//			}
//            
//			// STEP 4: format a Label server control to display a custom time greeting based on the time zone of the client page
//			Label lblTimeStamp = new Label();
//			DateTime current = DateTime.Now.AddHours(TimeDiffFromEST);
//			DateTime startTime = DateTime.Parse("9:00:00 AM").AddHours(TimeDiffFromEST);
//			DateTime endTime = DateTime.Parse("4:00:00 PM").AddHours(TimeDiffFromEST);
//            
//			if(current.DayOfWeek.ToString() != "Saturday" && current.DayOfWeek.ToString() != "Sunday")
//			{
//				if((current - startTime).Hours < 0 && (endTime - current).Hours > 0)
//				{
//					lblTimeStamp.Text = "The market is open...data as of " + DateTime.Now.AddHours(TimeDiffFromEST).ToLongTimeString();
//				}
//				else
//				{
//					lblTimeStamp.Text = "The market has closed";
//				}
//			}
//			else
//			{
//				lblTimeStamp.Text = "The market is closed on weekends";
//			}
//            
//			// STEP 5: add the content to the Page object's control tree
//			this.Controls.Add(new LiteralControl(code));
//			this.Controls.Add(new LiteralControl("<marquee id=\"" + ClientID + "\" onMouseOut=\"start();\" onMouseOver=\"stop();\" bgcolor=\"" + BackgroundColor + "\" width=\"100%\" scrolldelay=\"2\" scrollamount=\"2\" loop=\"infinite\">"));
//			this.Controls.Add(xmlStockData);
//			this.Controls.Add(new LiteralControl("</marquee><br/><br/>"));
//			this.Controls.Add(lblTimeStamp);
//			this.Controls.Add(new LiteralControl("<br/>Data provided courtesy of <a target=\"_blank\" href=\"http://www.nasdaq.com\">NASDAQ</a>"));
//		}    
        
//		protected void Page_Load(object sender, EventArgs e)
//		{
//			EnsureChildControls();
//		}
	}
}
